package com.yanqu.road.server.manager.union.huaben;

import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.rank.cross.CrossUnionWeekRank;
import com.yanqu.road.entity.union.huaben.UnionHuaBenServerGroup;
import com.yanqu.road.entity.union.huaben.rank.HuaBenWeekServerGroup;
import com.yanqu.road.logic.bussiness.union.cross.CrossHuaBenBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.union.cross.UnionHuaBenProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manager.group.SystemGroupHelper;
import com.yanqu.road.server.manager.union.huaben.rank.CrossGroupWeekUnionRankListModel;
import com.yanqu.road.server.manger.UnionHuaBenServerGroupMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionHuaBenRankMgr extends TempMgr {

    //weekId groupId
    static Map<Integer, Map<Integer, HuaBenWeekServerGroup>> weekServerGroupMap = new ConcurrentHashMap<>();          //每周区服分组

    //weekId groupId type
    private static Map<Integer, Map<Integer, Map<Integer, CrossGroupWeekUnionRankListModel>>> groupWeekRankListModelMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        addServerGroupReloadListener();
        return reload();
    }

    private void addServerGroupReloadListener(){
        UnionHuaBenServerGroupMgr.addReloadListener(new ManagerReloadListener() {
            @Override
            public void notifyReload() {
                initCrossGroupWeekUnionRankListModel();

                notifyServerReload();
            }

        });
    }

    private void notifyServerReload() {
        SystemGroupHelper.notifyServerReload(eSystemId.CrossHuaBen.getValue());
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        int thisWeedId = CrossUnionHuaBenConfigMgr.getThisWeekId();
        int preWeedId = CrossUnionHuaBenConfigMgr.getPreWeekId();

        weekServerGroupMap = CrossHuaBenBussiness.getHuaBenWeekServerGroupMap(thisWeedId, preWeedId);
        initCrossGroupWeekUnionRankListModel();
        return true;
    }

    /**
     * 由每周业务数据生成榜单（不入库）
     */
    private void initCrossGroupWeekUnionRankListModel() {

        //业务数据 weekId,groupId,type
        Map<Integer, Map<Integer, Map<Integer, LinkedList<CrossUnionWeekRank>>>> data = CrossUnionHuaBenMgr.buildWeekRank();

        Map<Integer, Map<Integer, Map<Integer, CrossGroupWeekUnionRankListModel>>> rankModelMapTemp = new ConcurrentHashMap<>();

        for (Map.Entry<Integer, Map<Integer, Map<Integer, LinkedList<CrossUnionWeekRank>>>> entry : data.entrySet()) {
            int weekId = entry.getKey();
            if(rankModelMapTemp.get(weekId) == null){
                rankModelMapTemp.put(weekId, new ConcurrentHashMap<>());
            }
            Map<Integer, Map<Integer, CrossGroupWeekUnionRankListModel>> groupModelMap = rankModelMapTemp.get(weekId);
            for (Map.Entry<Integer, Map<Integer, LinkedList<CrossUnionWeekRank>>> groupEntry : entry.getValue().entrySet()) {
                int groupId = groupEntry.getKey();
                if(groupModelMap.get(groupId) == null){
                    groupModelMap.put(groupId, new ConcurrentHashMap<>());
                }
                Map<Integer, CrossGroupWeekUnionRankListModel> typeModelMap = groupModelMap.get(groupId);
                for (Map.Entry<Integer, LinkedList<CrossUnionWeekRank>> listEntry : groupEntry.getValue().entrySet()) {
                    int type = listEntry.getKey();
                    CrossGroupWeekUnionRankListModel model = new CrossGroupWeekUnionRankListModel(weekId, groupId);
                    model.setRankNum(GameConfig.UNION_STORY_RANK_NUM);
                    model.setRankList(listEntry.getValue());
                    typeModelMap.put(type, model);
                }
            }
        }

        groupWeekRankListModelMap = rankModelMapTemp;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {

        for (Map.Entry<Integer, Map<Integer, HuaBenWeekServerGroup>> mapEntry : weekServerGroupMap.entrySet()) {
            for (Map.Entry<Integer, HuaBenWeekServerGroup> groupEntry : mapEntry.getValue().entrySet()) {
                if(groupEntry.getValue().isInsertOption()){
                    CrossHuaBenBussiness.addHuaBenWeekServerGroup(groupEntry.getValue());
                }else if(groupEntry.getValue().isUpdateOption()){
                    CrossHuaBenBussiness.updateHuaBenWeekServerGroup(groupEntry.getValue());
                }
            }
        }

        return true;
    }

    /**
     * 更新榜单
     */
    public static void changeUnionRank(int weekId, long serverId, CrossUnionWeekRank unionWeekRank) {
        int groupId = UnionHuaBenServerGroupMgr.getGroupIdByServerId(serverId);

        CrossGroupWeekUnionRankListModel rankListModel = getCrossGroupWeekUnionRankListModel(weekId, groupId, unionWeekRank.getType());
        if(rankListModel == null){
            synchronized (groupWeekRankListModelMap){
                rankListModel = getCrossGroupWeekUnionRankListModel(weekId, groupId, unionWeekRank.getType());
                if(rankListModel == null){
                    if(!groupWeekRankListModelMap.containsKey(weekId)){
                        groupWeekRankListModelMap.put(weekId, new ConcurrentHashMap<>());
                    }
                    if(!groupWeekRankListModelMap.get(weekId).containsKey(groupId)){
                        groupWeekRankListModelMap.get(weekId).put(groupId, new ConcurrentHashMap<>());
                    }
                    if(!groupWeekRankListModelMap.get(weekId).get(groupId).containsKey(unionWeekRank.getType())){
                        rankListModel = new CrossGroupWeekUnionRankListModel(groupId, weekId);
                        groupWeekRankListModelMap.get(weekId).get(groupId).put(unionWeekRank.getType(), rankListModel);
                    }
                }
            }
            rankListModel = getCrossGroupWeekUnionRankListModel(weekId, groupId, unionWeekRank.getType());
        }
        if(rankListModel != null){
            rankListModel.rankChange(unionWeekRank);
        }
    }

    public static CrossGroupWeekUnionRankListModel getCrossGroupWeekUnionRankListModel(int weekId, int groupId, int type){
        if (!groupWeekRankListModelMap.containsKey(weekId)) {
            return  null;
        }
        Map<Integer, CrossGroupWeekUnionRankListModel> modelMap = groupWeekRankListModelMap.get(weekId).get(groupId);
        if(modelMap == null){
            return null;
        }
        return modelMap.get(type);
    }

    /**
     * 获取上周区服分组
     */
    public static int getWeekServerGroup(int weekId, long serverId){
        if(!weekServerGroupMap.containsKey(weekId)){
            return (int)serverId;
        }
        Map<Integer, HuaBenWeekServerGroup> serverGroupMap = weekServerGroupMap.get(weekId);
        for (Map.Entry<Integer, HuaBenWeekServerGroup> groupEntry : serverGroupMap.entrySet()) {
            if(groupEntry.getValue().getServerList().contains(serverId)){
                return groupEntry.getKey();
            }
        }
        return (int)serverId;
    }

    /**
     * 商会榜单
     */
    public static List<UnionHuaBenProto.UnionHuaBenUnionWeekRankTempMsg> parseUnionRankListMsg(LinkedList<CrossUnionWeekRank> rankList) {
        List<UnionHuaBenProto.UnionHuaBenUnionWeekRankTempMsg> result = new ArrayList<>();
        int size = rankList.size();
        for (int i = 0; i < size; i++) {
            CrossUnionWeekRank unionWeekRank = rankList.get(i);
            UnionHuaBenProto.UnionHuaBenUnionWeekRankTempMsg.Builder builder = UnionHuaBenProto.UnionHuaBenUnionWeekRankTempMsg.newBuilder();
            builder.setValue(unionWeekRank.getValue().toString());
            builder.setParam(unionWeekRank.getParam());
            builder.setUnionUid(unionWeekRank.getUnionUid());
            builder.setUnionBaseData(UnionBasePb.parseUnionBaseTempMsg(unionWeekRank.getUnionBaseInfo()));
            result.add(builder.build());
        }
        return result;
    }

    /**
     * 锁定每周区服分组
     */
    public static void lockPreWeekServerGroup(){
        int preWeekId = getPreWeekId();
        if(!weekServerGroupMap.containsKey(preWeekId)){
            Map<Integer, HuaBenWeekServerGroup> serverGroupMap = new ConcurrentHashMap<>();
            List<UnionHuaBenServerGroup> serverGroupList = UnionHuaBenServerGroupMgr.getServerGroupList(ConfigHelper.getInt("channelId"));
            for (UnionHuaBenServerGroup serverGroup : serverGroupList) {
                HuaBenWeekServerGroup weekServerGroup = new HuaBenWeekServerGroup();
                weekServerGroup.setGroupId(serverGroup.getGroupId());
                weekServerGroup.setWeekId(preWeekId);
                for(long sid : serverGroup.getServerList()) {
                    weekServerGroup.getServerList().add(sid);
                }
                weekServerGroup.setInsertOption();
                serverGroupMap.put(serverGroup.getGroupId(), weekServerGroup);
            }
            weekServerGroupMap.put(preWeekId, serverGroupMap);
        }
    }

    /**
     * 前一周id(周日22点后)
     */
    public static int getPreWeekId() {
        Calendar now = Calendar.getInstance();
        //如果是周天
        if(now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
            long zeroTime = DateHelper.getTodayZeroTimeStamp();
            //22点后，返回本周零点
            if(now.getTimeInMillis() >= (zeroTime + GameConfig.UNION_STORY_END_TIME * DateHelper.HOUR_MILLIONS)){
                Date monday = DateHelper.getThisWeekMonday(now.getTime());
                now.setTime(monday);
            }else {
                Date monday = DateHelper.getThisWeekMonday(now.getTime());
                now.setTime(monday);
                now.add(Calendar.HOUR, -7 * 24);
            }
        }else {
            Date monday = DateHelper.getThisWeekMonday(now.getTime());
            now.setTime(monday);
            now.add(Calendar.HOUR, -7 * 24);
        }
        return Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
    }

    /**
     * 本周id
     */
    public static int getThisWeekId(){
        Calendar now = Calendar.getInstance();
        //如果是周天
        if(now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
            long zeroTime = DateHelper.getTodayZeroTimeStamp();
            //22点后，返回后一天零点
            if(now.getTimeInMillis() >= (zeroTime + GameConfig.UNION_STORY_END_TIME * DateHelper.HOUR_MILLIONS)){
                now.setTimeInMillis(zeroTime);
                now.add(Calendar.HOUR, 24);
            }else {
                Date monday = DateHelper.getThisWeekMonday(now.getTime());
                now.setTime(monday);
            }
        }else {
            Date monday = DateHelper.getThisWeekMonday(now.getTime());
            now.setTime(monday);
        }
        return Integer.valueOf(DateHelper.getPyyyyMMddDateString(now.getTimeInMillis() / 1000));
    }

    public static boolean isSunDayLast4Hour(){
        Calendar now = Calendar.getInstance();
        //如果是周天
        if(now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            long zeroTime = DateHelper.getTodayZeroTimeStamp();
            //22点后
            if(now.getTimeInMillis() >= (zeroTime + GameConfig.UNION_STORY_END_TIME * DateHelper.HOUR_MILLIONS)){
                return true;
            }
        }
        return false;
    }

    public static Map<Integer, Map<Integer, Map<Integer, CrossGroupWeekUnionRankListModel>>> getGroupWeekRankListModelMap() {
        return groupWeekRankListModelMap;
    }
}
